#define  _CRT_SECURE_NO_WARNINGS 1

#include "Queue.h"

void QueueInit(pQueue pq)
{
	assert(pq);

	pq->phead = pq->ptail = NULL;
	pq->size = 0;

}

pQNode BuyQueueNode(QDataType data)
{
	pQNode newnode = (pQNode)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->val = data;
	newnode->next = NULL;

	return newnode;
}

void QueuePush(pQueue pq, QDataType data)
{
	assert(pq);

	pQNode newnode = BuyQueueNode(data);
	if (pq->phead == NULL)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}

	++pq->size;

}

void QueuePop(pQueue pq)
{
	assert(pq && pq->phead);

	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = pq->ptail = NULL;
	}
	else
	{
		pQNode next = pq->phead->next;
		free(pq->phead);
		pq->phead = next;
	}

	--pq->size;
}

bool QueueEmpty(pQueue pq)
{
	assert(pq);

	return pq->phead == NULL;
}

QDataType QueueFront(pQueue pq)
{
	assert(pq && pq->phead);

	return pq->phead->val;
}

QDataType QueueBack(pQueue pq)
{
	assert(pq && pq->phead);

	return pq->ptail->val;
}

int QueueSize(pQueue pq)
{
	assert(pq);

	return pq->size;
}

void QueueDestory(pQueue pq)
{
	assert(pq);

	pQNode cur = pq->phead;
	while (cur)
	{
		pQNode next = cur->next;
		free(cur);
		cur = next;
	}

	pq->phead = pq->ptail = NULL;
	pq->size = 0;

}